<template>
  <el-input
    v-model="filterText"
    size="small"
    placeholder="输入关键字进行过滤"
  >
    <template #append>
      <el-button icon="Search" />
    </template>
  </el-input>

  <div class="mt-2">
    <el-scrollbar height="400px">
      <el-tree
        :expand-on-click-node="false"
        ref="treeRef"
        highlight-current
        :props="props"
        :load="loadNode"
        @node-click="handleNodeClick"
        lazy
        :filter-node-method="filterNode"
      />
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, defineEmits } from 'vue'
  import type Node from 'element-plus/es/components/tree/src/model/node'
  import { ElTree } from 'element-plus'

  import {getOrgList} from "@/api/ERP_sales";
  import {OrgNode} from "@/views/ERP_sales/type/sales_type";

  const emit = defineEmits(['change'])
  // 节点点击事件的处理函数
  function handleNodeClick(nodeData, node, component) {
    // 使用 emit 触发 change 事件，并传递节点数据
    console.log('node', node)
    emit('change', nodeData);
  }

  interface Tree {
    [key: string]: any
  }

  const filterText = ref('')
  const treeRef = ref<InstanceType<typeof ElTree>>()

  const props = {
    label: 'deptName',
    children: 'children',
    isLeaf: 'hasChildren',
  }

  watch(filterText, (val) => {
    treeRef.value!.filter(val)
  })
  const filterNode = (value, data) => {
    return data.deptName.includes(value)
  }
  const loadNode = async (node: any, resolve: Function) => {
    const nodeId = node.data.id;
    const params: ApiParams = {};
    if (nodeId) {
      params.parentId = nodeId
    }
    const childrenData = await getOrgList(params);
    const data =  childrenData.data.map((item: any) => ({
      id: item.id,
      deptName: item.deptName,
      parentId: item.parentId,
      hasChildren: !item.hasChildren,
      children: []
    }));
    resolve(data);
  };


</script>
